package com.bbbug.coree.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbbug.coree.entity.Roominfo;
import com.bbbug.coree.entity.Userinfo;
import com.bbbug.coree.service.RooominfoService;
import com.bbbug.coree.service.UserinfoService;
import com.bbbug.coree.utils.MiscUtil;
import com.bbbug.coree.entity.ReturnData;


import com.bbbug.coree.utils.SpringUtils;
import com.bbbug.coree.utils.Thirdlogin;
import com.bbbug.coree.websocketservice.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.yeauty.pojo.Session;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * (Userinfo)表控制层
 *
 * @author Zixiang Gao
 * @since 2021-06-23 18:15:15
 */
@RestController
@CrossOrigin( )
@RequestMapping("api/user")
public class UserinfoController {
    @Autowired
    private Thirdlogin thirdlogin;
     private RedisTemplate redisTemplate= SpringUtils.getBean("redistemp");
    @Autowired
    private UserinfoService service;
    @Autowired
    private RooominfoService roominfoService;
    public Userinfo getUserbyemail(String email){
        Userinfo userinfo  = service.queryByAccount(email);
        return userinfo;
    }
    @RequestMapping("/getmyinfo")
    public ReturnData getUserinfoService(@RequestBody JSONObject request) {
        String access_token = request.getString("access_token");
        String s = MiscUtil.verifyToken(access_token);
        if(s==null){
            Map<String, Object> map = new HashMap();
            map.put("user_id",-1);
            map.put("user_name","Ghost");
            map.put("user_head","new/images/guest.png");
            map.put("user_shutdown",1);
            return new ReturnData(200,"",map);
        }
        Map<String, Object> map = new HashMap();

        if(s==null) {
            return new ReturnData(401,"登录过期，请重新登录",map);
        } else{
            Map<String, Object> temp = BeanUtil.beanToMap(service.queryById(Integer.parseInt(s)));
            List<Roominfo> roominfos = roominfoService.queryByadmin(Integer.parseInt(s));
            if(roominfos.size()==0){
                temp.put("myRoom",false);
            }
            else{
                temp.put("myRoom",roominfos.get(0));
            }

            return new ReturnData(200,"",temp);
        }
    }
    public boolean isnull(String str){
        if(str == null || "".equals(str)){
            return true;
        }
        return false;
    }
    public boolean judge(String user,String password){
        if(isnull(user)||isnull(password)){
            return false;
        }

        return judgebymysql(user, password)||judgebyredis(user,password);
    }
    public boolean judgebymysql(String user,String password){

        Userinfo userinfo = service.queryByBoth(user,password);
        return userinfo!=null;
    }
    public boolean judgebyredis(String user,String password){
        BoundHashOperations emailcode = redisTemplate.boundHashOps("emailcode");
        JSONObject usercode;
        if(emailcode==null) {
            return false;
        }
         usercode=(JSONObject) emailcode.get(user);
        if(usercode==null){
            return false;
        }
         if(usercode.getLong("time")<System.currentTimeMillis()){
             emailcode.delete(user);
             return false;
         }

        return Objects.equals(usercode.getString("code"), password);
    }
    public boolean register(String user,String password){
        Userinfo userinfo = new Userinfo();
        userinfo.setUser_account(user);
        userinfo.setUser_passwd(password);
        userinfo.setUser_name("用户"+ RandomUtil.randomString(4));
        userinfo.setUser_sex(0);
        userinfo.setUser_head("new/images/nohead.png");
        userinfo.setUser_touchtip("头");
        return service.insert(userinfo);
    }

     @RequestMapping("login")
     public ReturnData login(@RequestBody JSONObject userinfo){
         System.out.println("1");
         String user_account = userinfo.getString("user_account");
         String user_password = userinfo.getString("user_password");
         if(user_password==null){
             user_password=userinfo.getString("user_passwd");
         }
        if(judge(user_account,user_password)){
            Userinfo userbyemail = getUserbyemail(user_account);
            if(userbyemail==null){
                register(user_account,user_password);
                userbyemail = getUserbyemail(user_account);
            }
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("access_token", MiscUtil.createToken(userbyemail.getUser_id().toString()));
            return new ReturnData(200,"登陆成功",objectObjectHashMap);
        }
        return new ReturnData(500,"账号密码有误",null);
    }

    @RequestMapping("thirdlogin")
    ReturnData thirdlogin(@RequestBody JSONObject mp){
        String from = mp.getString("from");
        String code = mp.getString("code");
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token","65536");
        Userinfo loginbyplat = thirdlogin.loginbyplat(code, from);
        map.put("access_token",loginbyplat==null?"65536":MiscUtil.createToken(loginbyplat.getUser_id().toString()));
        return new ReturnData(200,"",map);
    }
    @RequestMapping("updateMyInfo")
    public ReturnData updateMyInfo(@RequestBody JSONObject mp){
        String access_token = mp.getString("access_token");
        if(MiscUtil.verifyToken(access_token)==null){
            return new ReturnData(401,"无权修改",null);
        }
        Userinfo userinfo=new Userinfo();
        userinfo.setUser_id(mp.getInteger("user_id"));
        userinfo.setUser_head(mp.getString("user_head"));
        userinfo.setUser_name(mp.getString("user_name"));
        userinfo.setUser_passwd(mp.getString("user_password"));
        userinfo.setUser_sex(mp.getInteger("user_sex"));
        userinfo.setUser_remark(mp.getString("user_remark"));
        userinfo.setUser_touchtip(mp.getString("user_touchtip"));
        if(service.update(userinfo)==false){
            return new ReturnData(401,"修改失败",null);
        }
        return new ReturnData(200,"修改成功",null);
    }

    @RequestMapping("getuserinfo")
    ReturnData getUserInfo(@RequestBody JSONObject mp){
        Integer user_id = mp.getInteger("user_id");
        Map<String, Object> temp = BeanUtil.beanToMap(service.queryById(user_id));
        List<Roominfo> roominfos = roominfoService.queryByadmin(user_id);
        if(roominfos.size()==0){
            temp.put("myRoom",false);
        }
        else{
            temp.put("myRoom",roominfos.get(0));
        }

        Object appname = temp.get("appname");

        if(appname!=null) {
            temp.put("app_id", 2);
            String plat=appname.toString();
            if(plat.contains("gitee")) {
                temp.put("app_name","gitee");
            } else if(plat.contains("qq")) {
                temp.put("app_name","QQ");
            } else if(plat.contains("ding")) {
                temp.put("app_name","钉钉");
            } else if(plat.contains("oschina")) {
                temp.put("app_name","开源中国");
            } else {
                temp.put("app_name","野鸡三方");
            }
            temp.put("app_url","#");
        }
        temp.put("user_device","Windows");
        return new ReturnData(200,"查询成功",temp);
    }
    @RequestMapping("online")
    ReturnData online(@RequestBody JSONObject mp){
        try {
            Thread.sleep(1000);//此处是为了使Map加入后再获取 防止错乱
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Object room_id = mp.get("room_id");
        Vector vector=new Vector();
        Map shutdown = (Map) redisTemplate.boundHashOps("shutdown").get(room_id.toString());
        Map songdown = (Map) redisTemplate.boundHashOps("songdown").get(room_id.toString());
        if(shutdown==null) {
            shutdown=new HashMap();
        }
        if(songdown==null) {
            songdown=new HashMap();
        }
       for(String x:core.CHATMAP.get(room_id.toString()).keySet()){
          try{
              Map<String, Object> temp = BeanUtil.beanToMap(service.queryById(Integer.parseInt(x)));
              if(shutdown.get(x)!=null) {
                  temp.put("user_shutdown",1);
              }
              if(songdown.get(x)!=null) {
                  temp.put("user_songdown",1);
              }
              vector.add(temp);
          }catch (Exception e){
              //do nothing
          }
       }
       return new ReturnData(200,"userdata",vector);
    }
    @RequestMapping("shutdown")
    ReturnData shutdown(@RequestBody JSONObject mp){
        String access_token = mp.getString("access_token");
        String from=MiscUtil.verifyToken(access_token);
        if(from==null){
            return new ReturnData(403,"无权",null);
        }
        String room_id = mp.get("room_id").toString();
        String user_id = mp.get("user_id").toString();
        BoundHashOperations shutdown = redisTemplate.boundHashOps("shutdown");
        HashMap jinyanmp= (HashMap) shutdown.get(room_id);
        if(jinyanmp==null)jinyanmp=new HashMap();
        jinyanmp.put(user_id,System.currentTimeMillis()+15*1000*60);//使用传说中的序列化
        shutdown.put(room_id,jinyanmp);
        JSONObject shutdownmessage = new JSONObject();
        shutdownmessage.put("user",service.queryById(Integer.parseInt(from)));
        shutdownmessage.put("ban",service.queryById(Integer.parseInt(user_id)));
        shutdownmessage.put("type","shutdown");
        SendForALL(room_id,shutdownmessage.toJSONString());
        return new ReturnData(200,"禁言好了",null);
    }
    @RequestMapping("songdown")
    ReturnData songdown(@RequestBody JSONObject mp){
        String access_token = mp.getString("access_token");
        String from=MiscUtil.verifyToken(access_token);
        if(from==null){
            return new ReturnData(403,"无权",null);
        }
        String room_id = mp.get("room_id").toString();
        String user_id = mp.get("user_id").toString();
        BoundHashOperations shutdown = redisTemplate.boundHashOps("songdown");
        HashMap jinyanmp= (HashMap) shutdown.get(room_id);
        if(jinyanmp==null)jinyanmp=new HashMap();
        jinyanmp.put(user_id,System.currentTimeMillis()+15*1000*60);//使用传说中的序列化
        shutdown.put(room_id,jinyanmp);
        JSONObject shutdownmessage = new JSONObject();
        shutdownmessage.put("user",service.queryById(Integer.parseInt(from)));
        shutdownmessage.put("ban",service.queryById(Integer.parseInt(user_id)));
        shutdownmessage.put("type","songdown");
        SendForALL(room_id,shutdownmessage.toJSONString());
        return new ReturnData(200,"禁言好了",null);
    }
    @RequestMapping("guestctrl")
    ReturnData guestctrl(@RequestBody JSONObject mp){
        return new ReturnData(401,"我也不知道是啥东西的api",null) ;
    }
    @RequestMapping("removeban")
    ReturnData removeban(@RequestBody JSONObject mp){
        String access_token = mp.getString("access_token");
        String from=MiscUtil.verifyToken(access_token);
        if(from==null){
            return new ReturnData(403,"无权",null);
        }
        String room_id = mp.get("room_id").toString();
        String user_id = mp.get("user_id").toString();
        BoundHashOperations shutdown = redisTemplate.boundHashOps("shutdown");
        HashMap jinyanmp= (HashMap) shutdown.get(room_id);
        BoundHashOperations shutdown2 = redisTemplate.boundHashOps("songdown");
        HashMap songdown= (HashMap) shutdown2.get(room_id);
        int ans=0;
        if((jinyanmp==null||jinyanmp.get(user_id)==null)&&(songdown==null||songdown.get(user_id)==null)){
            return new ReturnData(200,"可能无事发生？",null);
        }
        else{
            if(jinyanmp.get(user_id)!=null){
                jinyanmp.remove(user_id);
                shutdown.put(room_id,jinyanmp);
                ans=1;
            }
            if(songdown.get(user_id)!=null){
                songdown.remove(user_id);
                shutdown2.put(room_id,songdown);
                ans=1;
            }
        }
        if(ans!=0){
            JSONObject shutdownmessage = new JSONObject();
            shutdownmessage.put("user",service.queryById(Integer.parseInt(from)));
            shutdownmessage.put("ban",service.queryById(Integer.parseInt(user_id)));
            shutdownmessage.put("type","removeban");
            SendForALL(room_id,shutdownmessage.toJSONString());
            return new ReturnData(200,"解除",null);
        }else{
            return new ReturnData(200,"成功但无事发生",null);
        }

    }
    boolean SendForALL(String room_id,String message) {

        ConcurrentHashMap<String, Session> stringSessionConcurrentHashMap = core.CHATMAP.get(room_id);
        if (stringSessionConcurrentHashMap == null) {
            return false;
        }
        for (Session value : stringSessionConcurrentHashMap.values()) {
            value.sendText(message);
        }
        return true;
    }

}